package com.loan.util;

import java.io.UnsupportedEncodingException;
import java.text.MessageFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

public class Str extends StringUtils {
	private final static Logger logger = Logger.getLogger(Str.class);
	public static final char UNDERLINE = '_';

	public static boolean nb(String str) {
		return StringUtils.isNotBlank(str);
	}

	public static boolean eq(String str1, String str2) {
		return StringUtils.equals(str1, str2);
	}

	public static boolean ne(String str1, String str2) {
		return !StringUtils.equals(str1, str2);
	}

	public static String format(String contents, Object... args) {
		return MessageFormat.format(contents, args);
	}

	// 驼峰转下横线
	public static String camelToUnderline(String param) {
		if (param == null || "".equals(param.trim())) {
			return "";
		}
		int len = param.length();
		StringBuilder sb = new StringBuilder(len);
		for (int i = 0; i < len; i++) {
			char c = param.charAt(i);
			if (Character.isUpperCase(c)) {
				sb.append(UNDERLINE);
				sb.append(Character.toLowerCase(c));
			} else {
				sb.append(c);
			}
		}
		return sb.toString();
	}

	// 下横线转驼峰
	public static String underlineToCamel(String param) {
		if (param == null || "".equals(param.trim())) {
			return "";
		}
		int len = param.length();
		StringBuilder sb = new StringBuilder(len);
		for (int i = 0; i < len; i++) {
			char c = param.charAt(i);
			if (c == UNDERLINE) {
				if (++i < len) {
					sb.append(Character.toUpperCase(param.charAt(i)));
				}
			} else {
				sb.append(c);
			}
		}
		return sb.toString();
	}

	public static String underlineToCamel2(String param) {
		if (param == null || "".equals(param.trim())) {
			return "";
		}
		StringBuilder sb = new StringBuilder(param);
		Matcher mc = Pattern.compile("_").matcher(param);
		int i = 0;
		while (mc.find()) {
			int position = mc.end() - (i++);
			// String.valueOf(Character.toUpperCase(sb.charAt(position)));
			sb.replace(position - 1, position + 1, sb.substring(position, position + 1).toUpperCase());
		}
		return sb.toString();
	}

	public static String filter(String message) {
		if (message == null)
			return (null);
		char content[] = new char[message.length()];
		message.getChars(0, message.length(), content, 0);
		StringBuilder result = new StringBuilder(content.length + 50);
		for (int i = 0; i < content.length; i++) {
			switch (content[i]) {
			case '<':
				result.append("<");
				break;
			case '>':
				result.append(">");
				break;
			case '&':
				result.append("&");
				break;
			case '"':
				result.append("\"");
				break;
			default:
				result.append(content[i]);
			}
		}
		return (result.toString());
	}

	/**
	 * subString("acd中央人民广播电台", 5, "..") 返回： “acd中央人民..”
	 * 
	 * @param text
	 *            原始字符串
	 * @param length
	 *            截取长度
	 * @param endWith
	 *            超过截取长度时，用来什么字符串省略代替，
	 * @return subString("acd中央人民广播电台", 5, "..") 返回： “acd中央人民..”
	 */
	public static String subString(String text, int length, String endWith) {
		if (isBlank(text))
			return "";
		int textLength = text.length();
		int byteLength = 0;
		StringBuffer returnStr = new StringBuffer();
		for (int i = 0; i < textLength && byteLength < length * 2; i++) {
			String str_i = text.substring(i, i + 1);
			if (str_i.getBytes().length == 1) {// 英文
				byteLength++;
			} else {// 中文
				byteLength += 2;
			}
			returnStr.append(str_i);
		}
		try {
			if (byteLength < text.getBytes("GBK").length) {// getBytes("GBK")每个汉字长2，getBytes("UTF-8")每个汉字长度为3
				returnStr.append(endWith);
			}
		} catch (UnsupportedEncodingException e) {
			logger.error(e.getMessage());
			e.printStackTrace();
		}
		return returnStr.toString();
	}

	/**
	 * 
	 * 基本功能：过滤所有以"<"开头以">"结尾的标签
	 * <p>
	 * 
	 * @param str
	 * @return String
	 */
	public static String filterHtml(String str) {
		if (isBlank(str)) {
			return "";
		}
		Pattern pattern = Pattern.compile("<([^>]*)>");
		Matcher matcher = pattern.matcher(str);
		StringBuffer sb = new StringBuffer();
		boolean result1 = matcher.find();
		while (result1) {
			matcher.appendReplacement(sb, "");
			result1 = matcher.find();
		}
		matcher.appendTail(sb);
		return sb.toString();
	}

	/**
	 * 
	 * 基本功能：过滤引号
	 * <p>
	 * 
	 * @param str
	 * @return String
	 */
	public static String filterXSS(String str) {
		if (isBlank(str)) {
			return "";
		}
		Pattern pattern = Pattern.compile("\"|\'");
		Matcher matcher = pattern.matcher(str);
		StringBuffer sb = new StringBuffer();
		boolean result1 = matcher.find();
		while (result1) {
			matcher.appendReplacement(sb, "");
			result1 = matcher.find();
		}
		matcher.appendTail(sb);
		return sb.toString().replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("\\+", "");
	}

	public static String nullToEmpty(String str) {
		if (str == null) {
			return "";
		}
		return str;
	}

	public static String replaceBlank(String str) {
		String dest = "";
		if (str != null) {
			Pattern p = Pattern.compile("\\s*|\t|\r|\n");
			Matcher m = p.matcher(str);
			dest = m.replaceAll("");
		}
		return dest;
	}

	/**
	 * 检查字符串是否不是<code>null</code>和空字符串<code>""</code>。
	 * <p/>
	 * 
	 * <pre>
	 * StringUtil.isNotEmpty(null)      = false
	 * StringUtil.isNotEmpty("")        = false
	 * StringUtil.isNotEmpty(" ")       = true
	 * StringUtil.isNotEmpty("bob")     = true
	 * StringUtil.isNotEmpty("  bob  ") = true
	 * </pre>
	 * 
	 * @param str
	 *            要检查的字符串
	 * @return 如果不为空, 则返回<code>true</code>
	 */
	public static boolean isNotEmpty(String str) {
		str = replaceBlank(str);
		return ((str != null) && (str.length() > 0));
	}

	/**
	 * 前面start位字符， 后面end位字符， 中间用endWith
	 */
	public static String subString2(String text, int start, int end, String endWith) {
		if (isBlank(text))
			return "";
		int textLength = text.length();
		String returnStr;
		if (textLength > start + end) {
			returnStr = text.substring(0, start) + endWith + text.substring(textLength - end, textLength);
		} else if (textLength > start && (textLength < start + end || textLength == start + end)) {
			returnStr = text.substring(0, start) + endWith;
		} else {
			returnStr = text.substring(0, 1) + endWith;
		}

		return returnStr.toString();
	}

	/**
	 * 前面start位字符， 后面end位字符， 中间用endWith替换每个字符
	 */
	public static String subString3(String text, int start, int end, String endWith) {
		if (isBlank(text))
			return "";
		int textLength = text.length();
		String returnStr;
		String endWith2 = "";
		if (textLength > start + end) {
			for (int i = 0; i < textLength - (start + end); i++) {
				endWith2 = endWith2 + endWith;
			}
			returnStr = text.substring(0, start) + endWith2 + text.substring(textLength - end, textLength);
		} else if (textLength > start && (textLength < start + end || textLength == start + end)) {
			for (int i = 0; i < textLength - start; i++) {
				endWith2 = endWith2 + endWith;
			}
			returnStr = text.substring(0, start) + endWith2;
		} else {
			for (int i = 0; i < textLength - 1; i++) {
				endWith2 = endWith2 + endWith;
			}
			returnStr = text.substring(0, 1) + endWith2;
		}

		return returnStr.toString();
	}

	/**
	 * 截取text中某两个字符间的字符串
	 * 
	 * @Param text 原字段
	 * @param startStr
	 *            起始字符
	 * @param endString
	 *            结束字符
	 * @param includeStr
	 *            是否包含目标字符
	 */
	public static String subByStr(String text, String startStr, String endString, Boolean includeStr) {
		String returnStr = "";
		if (isBlank(text))
			return returnStr;
		int strIndex = text.indexOf(startStr);
		int endIndex = text.lastIndexOf(endString);
		if (strIndex > -1 && endIndex > -1) {
			if (includeStr) {
				returnStr = text.substring(strIndex, endIndex + 1);
			} else {
				returnStr = text.substring(strIndex + 1, endIndex);
			}
		} else {
			returnStr = text;
		}

		return returnStr.toString();
	}

	public static String replaceStrToStr(String source, String str0, String replace) {

		if (Str.isNotEmpty(source)) {
			if (source.indexOf(str0) > -1) {
				source = source.replace(str0, replace);
			}
		}
		return source;
	}

	public static int stringToInt(String intstr) {
		try {
			Integer integer;
			integer = Integer.valueOf(intstr);
			return integer.intValue();
		} catch (Exception e) {
			logger.info("字符串转换为整型失败", e);
		}
		return 0;
	}

	/**
	 * 隐藏手机号中间4位
	 */
	public static String hideMobile(String mobile) {
		return mobile.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
	}

	/**
	 * 返回随机手机号码
	 */
	public static String getTel() {
		String[] telFirst = "134,135,136,137,138,139,150,151,152,157,158,159,130,131,132,155,156,133,153".split(",");
		int index = (int) (Math.random() * (telFirst.length - 1));
		String first = telFirst[index];
		String second = String.valueOf((int) (Math.random() * (888 - 1 + 1) + 1) + 10000).substring(1);
		String third = String.valueOf((int) (Math.random() * (9100 - 1 + 1) + 1) + 10000).substring(1);
		return first + second + third;
	}

	public static int getNum(String str) {
		String regEx = "[^0-9]";
		Pattern p = Pattern.compile(regEx);
		Matcher m = p.matcher(str);
		String res = m.replaceAll("").trim();
		int num = Str.nb(res) ? Integer.valueOf(res) * 10 : 0;
		String letter = str.replaceAll("[^A-Z]", "");
		if (Str.nb(letter)) {
			num += (int) letter.charAt(0) - 64;
		}
		return num;
	}

	private static boolean isEmojiCharacter(char codePoint) {
		return (codePoint == 0x0) || (codePoint == 0x9) || (codePoint == 0xA) || (codePoint == 0xD)
				|| ((codePoint >= 0x20) && (codePoint <= 0xD7FF)) || ((codePoint >= 0xE000) && (codePoint <= 0xFFFD))
				|| ((codePoint >= 0x10000) && (codePoint <= 0x10FFFF));
	}

	/**
	 * 过滤emoji 或者 其他非文字类型的字符
	 *
	 * @param source
	 * @return
	 */
	public static String filterEmoji(String source) {
		if (StringUtils.isBlank(source)) {
			return source;
		}
		StringBuilder buf = null;
		int len = source.length();
		for (int i = 0; i < len; i++) {
			char codePoint = source.charAt(i);
			if (isEmojiCharacter(codePoint)) {
				if (buf == null) {
					buf = new StringBuilder(source.length());
				}
				buf.append(codePoint);
			}
		}
		if (buf == null) {
			return source;
		} else {
			if (buf.length() == len) {
				buf = null;
				return source;
			} else {
				return buf.toString();
			}
		}
	}
}
